package com.villaday.idf.activity3;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.adapter.JiafanJiluAdapter;
import com.villaday.idf.adapter3.DiscreteScrollViewOptions;
import com.villaday.idf.adapter3.JiaFanHeadAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.JiafanDialog;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.model3.Add_brokerage_boostersEntity;
import com.villaday.idf.model3.Add_brokerage_newestEntity;
import com.villaday.idf.model3.Add_brokerage_posterEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;
import com.yarolegovich.discretescrollview.DSVOrientation;
import com.yarolegovich.discretescrollview.DiscreteScrollView;
import com.yarolegovich.discretescrollview.transform.ScaleAndAlphaTransformer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/*
 * 加返活动页
 * */
public class JiaFanActivity extends BaseActivity implements OkHttpUtil.OnDataListener, ViewPager.OnPageChangeListener, OnAdapterCallbackListener {


    @BindView(R.id.toolbar_text)
    Toolbar toolbarText;
    @BindView(R.id.tv_leiji)
    TextView tvLeiji;
    @BindView(R.id.tv_yijihuo)
    TextView tvYijihuo;
    @BindView(R.id.tv_daijihuo)
    TextView tvDaijihuo;
    @BindView(R.id.vp)
    DiscreteScrollView vp;
    @BindView(R.id.tv_vp)
    TextView tvVp;
    @BindView(R.id.tv_des)
    TextView tvDes;
    @BindView(R.id.rv_jl)
    RecyclerView rvJl;
    @BindView(R.id.tv_vip)
    TextView tvVip;
    @BindView(R.id.tv_svip)
    TextView tvSvip;
    @BindView(R.id.tv_fs)
    TextView tv_fs;


    private Gson gson = new GsonBuilder().create();
    private LoadingDialog loadingDialog;
    private Add_brokerage_newestEntity fbe;
    private int pageNo = 1;
    private int nextIndex = 1;
    private int pageSize = 4;

    private List<ImageView> imgs = new ArrayList<>();
    private List<Add_brokerage_newestEntity.BodyEntity.TemplateListEntity> templateList = new ArrayList<>();
    private JiaFanHeadAdapter jiaFanHeadAdapter;

    private JiafanJiluAdapter jiafanJiluAdapter;

    List<Add_brokerage_boostersEntity.BodyEntity.ListEntity> data = new ArrayList<>();
    private int position = -1;
    private RefreshtokenEntity.BodyBean roleInfo;


    @Override
    protected int getViewResId() {
        return R.layout.activity_jia_fan;
    }

    @Override
    protected void init() {
        ToolBarUtil.initToolBar(toolbarText, "爱订房加返活动", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        roleInfo = SharedPreferencesUtil.getRoleInfo(this);
        if (roleInfo != null && "2".equals(roleInfo.getMember().getType())&&!"0".equals(roleInfo.getMember().getLevel())) {//svip
            tvSvip.setVisibility(View.VISIBLE);
        } else {
            tvSvip.setVisibility(View.GONE);

        }
        //rvJl.setLayoutManager(new LinearLayoutManager(this));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        linearLayoutManager.setAutoMeasureEnabled(true);

        rvJl.setLayoutManager(linearLayoutManager);
        rvJl.setHasFixedSize(true);
        //rvJl.setNestedScrollingEnabled(false);
        jiafanJiluAdapter = new JiafanJiluAdapter(this, this);
        rvJl.setAdapter(jiafanJiluAdapter);


    }

    @Override
    protected void loadData() {
        loadingDialog = LoadingDialog.newInstance("加载中...");
        loadingDialog.show(getFragmentManager());
        OkHttpUtil.getJSON(this, Constant.URL.add_brokerage_newest, this);
    }

    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.add_brokerage_newest.equals(url)) { //加返活动详情
                LogeUtil.e("add_brokerage_newest", json);
                fbe = gson.fromJson(json, Add_brokerage_newestEntity.class);
                if (Constant.Strings.SUC.equals(fbe.getCode())) {

                    getData();
                    final Add_brokerage_newestEntity.BodyEntity body = fbe.getBody();
                    tvLeiji.setText(Html.fromHtml("&yen;" + body.getTotalAddBrokerageAmountValue()));
                    tvYijihuo.setText(Html.fromHtml("&yen;" + body.getUnfrozenAddBrokerageAmountValue()));
                    tvDaijihuo.setText(Html.fromHtml("&yen;" + body.getFrozenAddBrokerageAmountValue()));
                    tvDes.setText(body.getRule());
                    templateList.clear();
                    templateList.addAll(fbe.getBody().getTemplateList());

                 /*   mInfiniteAdapter = InfiniteScrollAdapter.wrap(new JiaFanHeadAdapter(templateList, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        }
                    }));*/

                    vp.setSlideOnFling(true);

                    vp.setOrientation(DSVOrientation.HORIZONTAL);
                    vp.addOnItemChangedListener(new DiscreteScrollView.OnItemChangedListener<RecyclerView.ViewHolder>() {
                        @Override
                        public void onCurrentItemChanged(@Nullable RecyclerView.ViewHolder viewHolder, int adapterPosition) {
                            position = adapterPosition;

                            tvVp.setText(position + 1 + "/" + body.getTemplateList().size());

                        }
                    });

                    vp.setAdapter(new JiaFanHeadAdapter(templateList, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        }
                    }));
                    vp.setItemTransitionTimeMillis(DiscreteScrollViewOptions.getTransitionTime());
                    vp.setItemTransformer(new ScaleAndAlphaTransformer.Builder()
                            .setMinScale(0.8f)
                            .setMinAlpha(0.5f)
                            .build());


                }
            }
            if (String.format(Constant.URL.add_brokerage_boosters, fbe.getBody().getId()).equals(url)) { //加返活动获取海报
                dismissLoading();
                LogeUtil.e("add_brokerage_boosters", json);
                Add_brokerage_boostersEntity boosters = gson.fromJson(json, Add_brokerage_boostersEntity.class);
                removeLoadingItem();
                if (Constant.Strings.SUC.equals(boosters.getCode())) {
                    if (pageNo == 1 && boosters.getBody().getList() != null && boosters.getBody() != null) {
                        data.clear();
                    }
                    data.addAll(boosters.getBody().getList());
                    if (boosters.getBody().isHasNext()) {
                        data.add(new Add_brokerage_boostersEntity.BodyEntity.ListEntity(1));
                        nextIndex = pageNo + 1;
                    } else {
                        addBaseLine();
                    }

                } else {
                    addBaseLine();
                }
                jiafanJiluAdapter.setData(data);
            }
        }
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo + "");
        map.put("pageSize", pageSize + "");
        OkHttpUtil.getJSON(this, String.format(Constant.URL.add_brokerage_boosters, fbe.getBody().getId()), map, this);
    }

    private void removeLoadingItem() {
        if (data.size() > 0) {
            if (data.get(data.size() - 1).getMyType() == 1) {
                data.remove(data.size() - 1);
            }
        }
    }

    private void addBaseLine() {
        if (pageNo != 1) {
            data.add(new Add_brokerage_boostersEntity.BodyEntity.ListEntity(2));
        }
    }

    @Override
    public void onFailure(String url, String error) {
        dismissLoading();
    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }


    @OnClick({R.id.tv_vip, R.id.tv_svip, R.id.tv_fs})
    public void onViewClicked(View view) {
        if (fbe==null||roleInfo==null){
            return;
        }
        switch (view.getId()) {
            case R.id.tv_vip: {
                getDataShare(1);
            }
            break;
            case R.id.tv_svip: {
                getDataShare(2);
            }
            break;
            case R.id.tv_fs: {
                getDataShare(3);

            }
            break;
        }
    }

    private void getDataShare(int upgrade) {
        if (position == -1) {
            return;
        }
        loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(getFragmentManager(), "loading");
        String activityId = fbe.getBody().getId();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("activityId", activityId + "");
        hashMap.put("upgrade", upgrade + "");
        hashMap.put("number", position + "");


        OkHttpUtil.getJSON(this, Constant.URL.add_brokerage_poster, hashMap, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                if (!TextUtils.isEmpty(json)) {
                    LogeUtil.e("add_brokerage_poster", json);
                    dismissLoading();
                    final Add_brokerage_posterEntity material_postersEntity = gson.fromJson(json, Add_brokerage_posterEntity.class);
                    if ("200".equals(material_postersEntity.getCode())) {

                        List<String> imgUrls = new ArrayList<>();
                        if (!TextUtils.isEmpty(material_postersEntity.getBody().getPoster())) {
                            // imgUrls.add(material_postersEntity.getBody().getPoster());
                        }

                        imgUrls.add(material_postersEntity.getBody().getPoster());


                        JiafanDialog jiafanDialog = JiafanDialog.newInstance(JiaFanActivity.this, imgUrls, material_postersEntity.getBody().getPoster(), material_postersEntity.getBody().getDescription());
                        jiafanDialog.show(JiaFanActivity.this.getFragmentManager());

                    } else {
                        ToastUtil.initToast(JiaFanActivity.this, material_postersEntity.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String url, String error) {
                dismissLoading();
            }
        });
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {

    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    @Override
    public void onCallback() {
        if (nextIndex == pageNo + 1) {
            pageNo++;
            getData();
        }
    }
}
